# -*- coding: utf-8 -*-
'''
author:Cooper
date:2012.5.14

desc: 完成数据处理操作
把API返回的JSON数据映射到数据库里面，完成JSON数据存储操作
'''

import json
from TopAPI.lib import parseJsonField,getConn
from TopAPI.config import mapping as mapping_tb_pk
from TopAPI.table_mapping import table_mapping as mapping_local_field

def getFiledType(tbName,field):
	db=getConn('TAOBAOAPI')
	db.query("SELECT TYPE FROM apidatastruct WHERE CLASS='%s' AND FIELD='%s'"%(tbName,field))
	r=db.store_result()
	if r.num_rows()==0:
		db.close()
		return None
	else:
		t=r.fetch_row()[0][0]
		if t.find('[]')!=-1:
			t=t[:t.find('[')].strip()
		db.close()
		return t

def getTbSelfPk(tbName):
	'''
	从mapping中获取表的主键list
	'''
	l=list()
	if mapping_tb_pk.has_key(tbName):
		for t in mapping_tb_pk[tbName]:
			if t['type'] not in ['self','session']:
				l.append(t['pk'])
	return l

def getPkValue(j,pkList):
	'''
	从dict中获取主键list对应的键值
	'''
	l=list()
	for t in pkList:
		if j.has_key(t):
			l.append(j[t])
		else:
			l.append('')
	return '+'.join(l)

def getParentPkValue(j,tbName):
	'''
	获取某个表的外键在JSON数据中对应的值
	'''
	l=[t['pk'] for t in mapping_tb_pk[tbName] if t['type'] not in ['self','session']]
	d={t:j[t] for t in l if j.has_key(t)}
	d.update({t:None for t in l if not j.has_key(t)})
	return d

def parseDDL(d,tbName):
	'''
	DDL生成脚本
	'''
	insert_template='INSERT INTO `%s` VALUES($VALUES$);'%tbName
	value_list=list()
	for field in mapping_local_field[tbName].split(','):
		if d[field]:
			if isinstance(d[field],unicode):
				#value_list.append(d[field].encode('utf-8'))
				value_list.append("'%s'"%d[field])
			else:
				value_list.append("'%s'"%str(d[field]))
		else:
			value_list.append('NULL')
	return insert_template.replace('$VALUES$',','.join(value_list+['NOW()']))

def parseJson(j,tbName,extd=dict()):
	'''
	param argv:外键
	'''
	#step 1:错误处理
	#j=parseJsonField(j,key)
	#if not j:return
	#step 2:外键依赖检查
	#step 3:字段赋值
	rs=list()
	d_field=dict()
	d_field.update(extd)
	foreign_keys=[t['pk'] for t in mapping_tb_pk[tbName] if t['type'] not in ['self']]
	for field in mapping_local_field[tbName].split(','):
		#if field in foreign_keys:
		#d_field[field]=argv[field]
		if d_field.has_key(field):continue
		if j.has_key(field):
			if isinstance(j[field],(list,dict)):
				#获取对象类型
				fieldType=getFiledType(tbName,field)
				if mapping_tb_pk.has_key(fieldType):
					if isinstance(j[field],dict):
						#对象，该键值为对象主键
						d_field[field]=getPkValue(j,getTbSelfPk(fieldType))
						#递归调用，保存子对象数据
						rs=rs+parseJson(j[field],fieldType,getParentPkValue(j,fieldType))
					else:
						#对象列表，该键值为对象主键集合
						pkList=getTbSelfPk(fieldType)
						d_field[field]=','.join(map(getPkValue,j,[pkList]*len(j[field])))
						#递归调用，保存子对象数据
						for t in j[field]:
							rs=rs+parseJson(t,fieldType,getParentPkValue(j,fieldType))
			else:
				d_field[field]=j[field]
		else:
			d_field[field]=None
	#键值赋值完毕，开始生成DDL语句
	return rs+[parseDDL(d_field,tbName)]

def main():
	from TopAPI.user import user
	u=user()
	u.setParams(nick='osa品牌服饰旗舰店')
	j=u.parseUser()
	print '\n'.join(parseJson(j,'User'))

if __name__ == '__main__':
	main()